import io.kubernetes.client.Copy;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.util.Streams;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;

import static config.KubeConfigure.GetKubeClient;

public class FileCopyUtil {
    /**
     * copy file from kubernetes path to local path
     * @param namespace
     * @param podName
     * @param srcPath
     * @param destPath
     * @throws IOException
     * @throws ApiException
     */
    public static void CopyFile2Local(String namespace, String podName, String srcPath, String destPath) {
        GetKubeClient();
        Copy copy = new Copy();
        InputStream dataStream = null;
        try {
            dataStream = copy.copyFileFromPod(namespace, podName, srcPath);
            Streams.copy(dataStream, new FileOutputStream(destPath));
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * copy file from local path to kubernetes path
     * @param namespace
     * @param podName
     * @param container
     * @param srcPath
     * @param destPath
     * @throws IOException
     * @throws ApiException
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void CopyFile2Pod(String namespace, String podName, String container, String srcPath, String destPath) {
        GetKubeClient();
        Copy copy = new Copy();
        try {
            copy.copyFileToPodAsync(namespace, podName, container, Paths.get(srcPath), Paths.get(destPath));
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
